/**
 * Cesium自带控件以及各种图层的加载，图层也可以通过index去展示
 * 具体详情查阅官方文档
 */
var viewer = new Cesium.Viewer("cesiumContainer", {
  animation: true,//左下角时间动画罗盘
  timeline: true,//正下方时间线
  selectionIndicator: true,
  baseLayerPicker: true,//图层选择器
  fullscreenButton: true,//全屏按钮
  vrButton: true,//是否开启VR模式
  geocoder: true,//查找控件
  homeButton: true,//home控件
  sceneModePicker: true,//选择视角的模式
  creditContainer: null,
  infoBox: true,
  navigationHelpButton: true,//帮助控件
  imageryProvider: new Cesium.UrlTemplateImageryProvider({//加载高德地图图层
    // url:"//www.google.cn/maps/vt?lyrs=s,h&gl=CN&x={x}&y={y}&z={z}",
    url: "http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
    subdomains: ["1", "2", "3", "4"]
  }),
  // imageryProvider: new Cesium.UrlTemplateImageryProvider({
  //   url: "//www.google.cn/maps/vt?lyrs=s,h&gl=CN&x={x}&y={y}&z={z}",//加载谷歌地图图层
  //   //   url:  "http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
  //   subdomains: ["1", "2", "3", "4"]
  // }),
  // terrainProvider: new Cesium.CesiumTerrainProvider({//加载中国地理信息高度图层
  //     url: '//lab.earthsdk.com/terrain/577fd5b0ac1f11e99dbd8fd044883638',
  //     requestVertexNormals: true,
  //     requestWaterMask: true
  // })
});

var scene = viewer.scene;
var camera = scene.camera;
var handler;

let bufferGPSBillboards = new Cesium.EntityCollection(); // Billboard集合
var startMousePosition;
var mousePosition;
var flags = {
  looking: false,
  moveForward: false,
  moveBackward: false,
  moveUp: false,
  moveDown: false,
  moveLeft: false,
  moveRight: false,
};
var canvas = viewer.canvas;
canvas.setAttribute("tabindex", "0"); // needed to put focus on the canvas
canvas.onclick = function () {
  canvas.focus();
};
var ellipsoid = scene.globe.ellipsoid;

// disable the default event handlers
// scene.screenSpaceCameraController.enableRotate = false;
// scene.screenSpaceCameraController.enableTranslate = false;
// scene.screenSpaceCameraController.enableZoom = false;
// scene.screenSpaceCameraController.enableTilt = false;
// scene.screenSpaceCameraController.enableLook = false;
function getFlagForKeyCode(keyCode) {
  switch (keyCode) {
    case "W".charCodeAt(0):
      return "moveForward";
    case "S".charCodeAt(0):
      return "moveBackward";
    case "Q".charCodeAt(0):
      return "moveUp";
    case "E".charCodeAt(0):
      return "moveDown";
    case "D".charCodeAt(0):
      return "moveRight";
    case "A".charCodeAt(0):
      return "moveLeft";
    default:
      return undefined;
  }
}
document.addEventListener(
  "keydown",
  function (e) {
    var flagName = getFlagForKeyCode(e.keyCode);
    if (typeof flagName !== "undefined") {
      flags[flagName] = true;
    }
  },
  false
);

document.addEventListener(
  "keyup",
  function (e) {
    var flagName = getFlagForKeyCode(e.keyCode);
    if (typeof flagName !== "undefined") {
      flags[flagName] = false;
    }
  },
  false
);


//鼠标move悬浮框
var labelEntity = viewer.entities.add({
  label: {
    show: false,
    showBackground: true,
    font: "14px monospace",
    horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
    verticalOrigin: Cesium.VerticalOrigin.TOP,
    pixelOffset: new Cesium.Cartesian2(15, 0),
  },
});
//注册鼠标move事件
var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);

handler.setInputAction(function (movement) {
  flags.looking = false;
  mousePosition = startMousePosition = Cesium.Cartesian3.clone(
    movement.position
  );
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
handler.setInputAction(function (position) {
  flags.looking = false;
}, Cesium.ScreenSpaceEventType.LEFT_UP);

handler.setInputAction(function (movement) {
  var foundPosition = false;

    var scene = viewer.scene;
    if (scene.mode !== Cesium.SceneMode.MORPHING) {
      var pickedObject = scene.pick(movement.endPosition);
      if (
        scene.pickPositionSupported &&
        Cesium.defined(pickedObject) 
      ) {
        var cartesian = viewer.scene.pickPosition(movement.endPosition);

        if (Cesium.defined(cartesian)) {
          var cartographic = Cesium.Cartographic.fromCartesian(
            cartesian
          );
          var longitudeString = Cesium.Math.toDegrees(
            cartographic.longitude
          ).toFixed(2);
          var latitudeString = Cesium.Math.toDegrees(
            cartographic.latitude
          ).toFixed(2);
      

          labelEntity.position = cartesian;
          labelEntity.label.show = true;
          labelEntity.label.text =
            "经度: " +
            ("   " + longitudeString).slice(-7) +
            "\u00B0" +
            "\n纬度: " +
            ("   " + latitudeString).slice(-7) +
            "\u00B0" ;

          labelEntity.label.eyeOffset = new Cesium.Cartesian3(
            0.0,
            0.0,
            -cartographic.height *
              (scene.mode === Cesium.SceneMode.SCENE2D ? 1.5 : 1.0)
          );

          foundPosition = true;
        }
      }
    }

    if (!foundPosition) {
      labelEntity.label.show = false;
    }
  // var foundPosition = false;
  // mousePosition = movement.endPosition;
  // var pick = viewer.scene.pickPosition(movement.endPosition);  //获取的pick对象
  // if (Cesium.defined(pick)) {
  //   var cartographic = Cesium.Cartographic.fromCartesian(
  //     pick
  //   );
  //   var longitudeString = Cesium.Math.toDegrees(
  //     cartographic.longitude
  //   ).toFixed(2);
  //   var latitudeString = Cesium.Math.toDegrees(
  //     cartographic.latitude
  //   ).toFixed(2);
  //   var heightString = cartographic.height.toFixed(2);

  //   labelEntity.position = pick;
  //   labelEntity.label.show = true;
  //   labelEntity.label.text =
  //     "经度: " +
  //     ("   " + longitudeString).slice(-7) +
  //     "\u00B0" +
  //     "\n纬度: " +
  //     ("   " + latitudeString).slice(-7) +
  //     "\u00B0" +
  //     "\n高度: " +
  //     ("   " + heightString).slice(-7) +
  //     "m";

  //   labelEntity.label.eyeOffset = new Cesium.Cartesian3(
  //     0.0,
  //     0.0,
  //     -cartographic.height *
  //       (scene.mode === Cesium.SceneMode.SCENE2D ? 1.5 : 1.0)
  //   );
  //   foundPosition = true;
  //   console.log(1111)
  //     } else {
  //       // pickedEntity.point.color = Cesium.Color.WHITE;
  //     }
  //     if (!foundPosition) {
  //       labelEntity.label.show = false;
  //       console.log(2222)
  //     }
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);


viewer.clock.onTick.addEventListener(function (clock) {
  var camera = viewer.camera;

  if (flags.looking) {
    var width = canvas.clientWidth;
    var height = canvas.clientHeight;

    // Coordinate (0.0, 0.0) will be where the mouse was clicked.
    var x = (mousePosition.x - startMousePosition.x) / width;
    var y = -(mousePosition.y - startMousePosition.y) / height;
    

    var lookFactor = 0.05;
    camera.lookRight(x * lookFactor);
    camera.lookUp(y * lookFactor);
  }

  // Change movement speed based on the distance of the camera to the surface of the ellipsoid.
  var cameraHeight = ellipsoid.cartesianToCartographic(camera.position)
    .height;
  var moveRate = cameraHeight / 100.0;

  if (flags.moveForward) {
    camera.moveForward(moveRate);
  }
  if (flags.moveBackward) {
    camera.moveBackward(moveRate);
  }
  if (flags.moveUp) {
    camera.moveUp(moveRate);
  }
  if (flags.moveDown) {
    camera.moveDown(moveRate);
  }
  if (flags.moveLeft) {
    camera.moveLeft(moveRate);
  }
  if (flags.moveRight) {
    camera.moveRight(moveRate);
  }
});


function drawPoin(lat, lng, GPSDataw, GPSDatal) {
  let entity = bufferGPSBillboards.add(viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(lat, lng),
    point: {
      color: Cesium.Color.WHITE,
      pixelSize: 5.0,
    },
    description: "<table class=\"cesium-infoBox-defaultTable\"><tbody>" +
      "<tr><th>设备号</th><td style='text-align: center'>" + GPSDataw.DeviceCode + "</td></tr>" +
      "<tr><th>时间最外</th><td>" + GPSDataw.Time.$date + "</td></tr>" +
      "<tr><th>服务器接收时间</th><td>" + GPSDatal.RecieveTime.$date + "</td></tr>" +
      "<tr><th>GPS定位时间</th><td>" + GPSDatal.Gps.Time.$date + "</td></tr>" +
      "<tr><th>经纬度</th><td>" + lat.toFixed(6) + "," + lng.toFixed(6) + "</td></tr>" +
      "<tr><th>速度</th><td>" + GPSDatal.Gps.Speed + "</td></tr>" +
      "<tr><th>里程</th><td>" + GPSDatal.Gps.Mileage + "</td></tr>" +
      "<tr><th>方向</th><td>" + GPSDatal.Gps.Direction + "</td></tr>" +
      "</tbody></table>",
  }));

}
/**
 * 
 */
function setIndexDB(GPSData) {
  for (i = 0; i < GPSData.length; i++) {
    let id = GPSdata[i]._id.$oid;//indexDB KEY
    for (j = 0; j < GPSdata[i].Data.length; j++) {
      let wgs84togcj02 = coordtransform.wgs84togcj02(GPSdata[i].Data[j].Gps.Coordinates[0], GPSdata[i].Data[j].Gps.Coordinates[1]);
      GPSData[i].Data[j].Gps.Coordinates = wgs84togcj02;
      drawPoin(wgs84togcj02[0], wgs84togcj02[1], GPSdata[i], GPSdata[i].Data[j])
    }
    localforage.setItem(id, GPSData[i]).then(() => {
      console.log(i)
    })
  }
}

/**
 * for Dbug
 */
function loadGPSJson() {
  axios.get('../../data/KM-08_14146148433_LocationData202006.json')
    .then(function (response) {
      window.GPSdata = response.data;
      //  let GPSdata= JSON.parse(response.data)
      for (let i = 0; i < GPSdata.length; i++) {
        let id = GPSdata[i]._id.$oid;

        for (let z = 0; z < GPSdata[i].Data.length; z++) {

        }


      }
    })
    .catch(function (error) {
      console.log(error);
    });

}





